package net.m510.autosurfer.mhbk;

import java.net.URI;
import java.util.List;
import java.util.logging.Logger;

import net.m510.autosurfer.common.DocumentPostProcess;
import net.m510.autosurfer.common.exception.InvalidDocumentException;
import net.m510.autosurfer.core.Parameters;
import net.m510.autosurfer.core.utils.AnalyzeUtils;

import org.apache.http.NameValuePair;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.FormElement;
import org.jsoup.select.Elements;

/**
 * @author mgoto
 *
 */
public class MhbkLoginInputPassword extends DocumentPostProcess {
	private static final Logger log = Logger.getLogger(MhbkLoginInputPassword.class.getName());

	private String password;
	
	public MhbkLoginInputPassword() {
		this(null,null);
	}
	public MhbkLoginInputPassword(CloseableHttpClient client, HttpClientContext context) {
		super(client, context);
		super.log = log;
	}
	@Override
	protected URI getUri(Document doc) {
		Elements base = doc.getElementsByTag("base");
		if ( base == null ) throw new InvalidDocumentException("no base tag",doc);
		log.fine("base elem="+base);
		String href = base.first().attr("href");
		if ( href == null ) throw new InvalidDocumentException("no base href",doc);
		URI baseUri = URI.create(href);
		log.fine("base uri="+baseUri);
		final String FORM_ID="LOGBNK_00005B";
		FormElement form = AnalyzeUtils.getFormElementByName(doc, FORM_ID);
		if ( form == null ) throw new InvalidDocumentException("no form :"+FORM_ID,doc);
		return baseUri.resolve(form.attr("action"));
	}
	@Override
	protected List<NameValuePair> getRequestParameters(Document doc) {
		FormElement form = doc.getAllElements().forms().get(0);
		Parameters p = Parameters.create(form);
		p.put("PASSWD_LoginPwdInput", this.password);
		return p.asNameValueList();
	}

	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}